public class Solution1483 {

    int[][] f;

    public Solution1483(int n, int[] parent) {
        f=new int[n][16];
        for (int i=0;i<n;i++){
            f[i][0]=parent[i];
        }
        for (int i=1;i<16;i++){
            for (int j=0;j<n;j++){
                f[j][i]=f[j][i-1]!=-1?f[f[j][i-1]][i-1]:-1;
            }
        }
    }

    public int getKthAncestor(int node, int k) {
        int now=node;
        for (int i=0;i<16;i++){
            if ((k&(1<<i))!=0){
                now=f[now][i];
                if (now==-1){
                    break;
                }
            }
        }
        return now;
    }

    public static void main(String[] args) {
        Solution1483 solution1483=new Solution1483(5,new int[]{-1, 0, 0, 0, 3});
        System.out.println(solution1483.getKthAncestor(1,5));
    }
}
